package com.wzz.seckillone.activeMq.base;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @ProjectName: seckillOne
 * @Package: com.wzz.seckillone.activeMq
 * @ClassName: QueueConsumer
 * @Author: wzz
 * @Description:
 * @Date: 2022/3/21 9:12
 * @Version: 1.0
 */
public class QueueConsumer {
    private static final String ACTIVEMQ_URL = "tcp://192.168.1.104:61616";
    private static final String queueName = "queueOne";
/*
* activemq  事务和签收的关系：事务大于签收
* 在事务性会话中如果事务被成功commit则自动签收若事务回滚，则消息会被再次传递
* 非事务的会话中，要手动签收
*
*
* */
    public static void main(String[] args) throws JMSException, IOException {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        Connection connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        Queue queue = session.createQueue(queueName);
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener((message)->{
            if (message != null && message instanceof TextMessage){
                try {
                    TextMessage textMessage = (TextMessage)message;
                    System.out.println(textMessage.getText());
                    textMessage.acknowledge();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        /*消费者必须手动提交事务  否则会重复消费*/
        //session.commit();
        System.in.read();
        session.close();
        connection.close();
    }
}
